package org.adream.account.util;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;


/**
 * restful接口的认证，使用AOP切入
 * 
 * @author sunset shen
 *
 */
public class RestfulAuthenticatFilter  implements Filter  {
	
	Logger logger = LoggerFactory.getLogger(this.getClass());
	
	private static long timeout;
	
	static {
		//读取配置文件中的配置项
		String accountRestfulTimeout = Utils.readProperty("config/info.properties", "account.restful.timeout");
		timeout = StringUtils.isEmpty(accountRestfulTimeout) ? Constant.ACCOUNT_RESTFUL_TIMEOUT_DEFAULT : Long.parseLong(accountRestfulTimeout);		
	}
	
	@Override
	public void destroy() {
		 
		
	}
	
	private final static String SPORT_APPID = "D1d7PcW2EfcR4bw9aFF0cUfd8p45A9F2";
	
	public final static Map<String, String> AppMap = new HashMap<String, String>(); 
	static {  
		AppMap.put("Mgl7CcNQ2EzQEIjK4QGFAVvMolbodPj9", "pRXOadwG9OjYxWeaH7AcG3AVptmEoG2P");
		//智慧课堂appid，secret
		AppMap.put("p7d7C3NQ2E1QEIjKrQGFAVvMolb1dPjr", "p2XOadw091jYxWasH7AcG4ASp1mEoG2P");
		//爱数appid,secret
		AppMap.put("e80BF150656E41e2a00a507ef2Bb73b1", "d63FFb8aBfD14d0f9e9e1853b1eE592d");		
		//运动梦想课
		AppMap.put(SPORT_APPID, "OdbE8E04TcaP47Uibe2Y242Ce8dAfM7Q");
		}
			
			
	 
	//智慧课堂 接口权限 先写这  需要改配置目录 
	private final static List<String> LenovoApiList = new ArrayList<String>();
	//爱数 接口权限
	private final static List<String> aiShuApiList = new ArrayList<String>();
	static {
		LenovoApiList.add("getUserInfoByUid");
		LenovoApiList.add("getSchoolsInfo");
		LenovoApiList.add("doLogin");
		
		aiShuApiList.add("getUidsByResId");
	}
	//运动梦想课 接口权限
	private final static List<String> sprotClassApiList = new ArrayList<String>();
	static {
		sprotClassApiList.add("getUserVerifyInfo");
	}
	
 
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain fc)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		String appid = request.getParameter("appid");
		String timestamp = request.getParameter("timestamp");
		String signature = request.getParameter("signature");
		String bodyStr = request.getParameter("body");
		
		if(appid==null) {
			errMsg("appid不能为空",servletResponse);
			return;
		}
		
		//后期改成配置 目前先写 智慧课堂的
		String requestUrI = request.getRequestURI();
		String api = requestUrI.substring(requestUrI.lastIndexOf("/")+1);
		
		if("p7d7C3NQ2E1QEIjKrQGFAVvMolb1dPjr".equals(appid) && !LenovoApiList.contains(api)) {
			errMsg("appid权限不足",servletResponse);
			return;
		}
		
		if("e80BF150656E41e2a00a507ef2Bb73b1".equals(appid) && !aiShuApiList.contains(api)) {
			errMsg("appid权限不足",servletResponse);
			return;
		}
		
		//运动梦想课
		if(appid.equals(SPORT_APPID) && !sprotClassApiList.contains(api)) {
			errMsg("appid权限不足",servletResponse);
			return;
		}
		
		Long now = new Date().getTime();
		Long t = 0l ;
		
		try{
			t = Long.parseLong(timestamp);
		}catch(NumberFormatException e){
			logger.debug(e.getMessage(),e);
			errMsg("时间戳错误",servletResponse);	
			return;
		}
		if(Math.abs(now-t)>timeout){//10秒为妙,配置项
			logger.debug("now:" + now + ",,,,,,t:" + t);
			errMsg("操作过期，请校验服务器时间。",servletResponse);
			return;
		}else if(StringUtils.isEmpty(signature)||
				!signature.equals(PasswordUtil.md5Hex(AppMap.get(appid) + timestamp + (bodyStr==null?"":bodyStr)))){
			errMsg("非法调用。",servletResponse);
			 return;
		}
		
		if(!StringUtils.isEmpty(bodyStr)){
			@SuppressWarnings("unchecked")
			Map<String, Object> extraParams = JSON.parseObject(bodyStr, Map.class);
			RestfulServletRequestWrapper rw = new RestfulServletRequestWrapper(request);
			rw.setParameter("body", bodyStr);
			rw.setParameters(extraParams);
			fc.doFilter(rw, servletResponse);
		}else{
			fc.doFilter(request, servletResponse);
		}
	}
 
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
 	}
	
	private void errMsg(String errMsg,ServletResponse servletResponse) throws IOException {
		servletResponse.setContentType("application/json;charset=utf-8");
		PrintWriter pw = servletResponse.getWriter();
		pw.write("{\"returnCode\":9001,\"returnMsg\":\"");
		pw.write(errMsg);
		pw.write("\"}");
		pw.flush();
		pw.close();
	}
}

